package com.example.config.xss;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: AlbertHPW
 * @Date: 2025/6/15 19:08
 */
@WebFilter(urlPatterns = "/*")
public class XssFilter implements Filter {

    private final Set<String> whiteList = new HashSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化白名单
        whiteList.add("/api/rich-text");
        whiteList.add("/api/upload");
        whiteList.add("/api/file");
        whiteList.add("/api/image");

        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 排除特定路径，比如富文本上传接口
        String requestURI = request.getRequestURI();
        //if (requestURI.startsWith("/api/rich-text") || requestURI.startsWith("/api/upload")) {
        //    filterChain.doFilter(request, servletResponse);
        //    return;
        //}
        if(isWhiteListed(requestURI)) {
            filterChain.doFilter(request, servletResponse);
            return;
        }
        // 其他接口，进行XSS过滤
        XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper(request);
        filterChain.doFilter(wrapper, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private boolean isWhiteListed(String uri) {
        return whiteList.stream().anyMatch(uri::startsWith);
    }
}
